package com.qeegoo.b2bautozityp.moudle.home.view;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by HongQian.Wang on 2017/10/23.
 */

public class DownLoadService extends Service {

    private static final String TAG = "DownLoadService";
    private static final String DONDLOAD_PATH = Environment.getExternalStorageDirectory() + "/download/";


    public static final String DOWNLOAD_PROGRESS = "progress";

    public static final String ACTION_UPDATE = "action_update";

    private static final int DOWNLOAD_START = 0x000001;
    private String path;



    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_START:
                    new DownloadThread().start();

                    break;
            }
        }
    };
    private File file;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent!=null) {
            path = intent.getStringExtra("path");

            new InitThread().start();

        }

        return super.onStartCommand(intent, flags, startId);
    }

    class InitThread extends Thread {

        public void run() {
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            String location;
            try {
                URL url = new URL(DownLoadService.this.path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.connect();
                location = conn.getHeaderField("Location");
                path = location;
                conn.disconnect();
                conn = null;
                //获取重定向后的地址去联网
                URL urlRedirect = new URL(location);
                conn = (HttpURLConnection) urlRedirect.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.connect();



                int responseCode = conn.getResponseCode();

                if (responseCode == 200) {
                    int length = conn.getContentLength();
                    if (length <= 0) {
                        return;
                    }

                    File dir = new File(DONDLOAD_PATH);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    file = new File(dir.getAbsolutePath(), "update.apk");
                    raf = new RandomAccessFile(file, "rwd");
                    raf.setLength(length);
                    Message message = Message.obtain();
                    message.what = DOWNLOAD_START;
                    mHandler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (raf != null) {
                        raf.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                conn.disconnect();

            }
        }

    }


   public static boolean isCancel=false;
    class DownloadThread extends Thread {

        public void run() {
            HttpURLConnection conn = null;
            InputStream inputStream = null;
            RandomAccessFile raf = null;
            Intent intent = new Intent(ACTION_UPDATE);
            try {
                URL url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.connect();
                inputStream = conn.getInputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                int mFinished = 0;
                raf = new RandomAccessFile(file, "rwd");
                while ((len = inputStream.read(buffer)) >= 0) {
                    raf.write(buffer, 0, len);
                    mFinished += len;
                    intent.putExtra(DOWNLOAD_PROGRESS, mFinished);
                    intent.putExtra("fileLength", file.length());
                    DownLoadService.this.sendBroadcast(intent);
                    if(isCancel==true) {
                        break;
                    }
                }
                //ToDo 去安装
                if(isCancel==false) {
                    Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                    installIntent.setData(Uri.parse("file://" + file.getAbsolutePath()));
                    DownLoadService.this.startActivity(installIntent);
                }
                stopSelf();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (raf != null) {
                        raf.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                conn.disconnect();
            }


        }
    }
}
